#import cv  
import time
import math
import random
import pygame
import pygame.camera
from pygame.locals import *
import pyganim
from wordle import WordleWord
from frame_get import get_frame, string2Surface
import cv2.cv as cv


NUM_FISH = 5
DEPTH = 20
# SCREENSIZE = [1900,1080]
SCREENSIZE = [1024,800]

# SCREENSIZE = [1020,720]

smallres = (SCREENSIZE[0]/5, SCREENSIZE[1]/5)
GRAVITY = 9.81  #m/s^2
BUYOANCY = 9.2    #m/s^2
WATER_RESIS = 0.1 #L/s

WORDS = ['Images/Words/word%s.png'%(n) for n in xrange(1,1+NUM_FISH)]
FISH_POSITIONS = []

cascade = cv.Load("haarcascade_frontalface_default.xml")
image_res2 = (512, 400)
COUNT = 2

DETECTSIZE = (SCREENSIZE[0]/7,SCREENSIZE[1]/7)
#============================================================================================================================
def surface_to_string(surface):
    """Convert a pygame surface into string"""
    return pygame.image.tostring(surface, 'RGB')
  
def pygame_to_cvimage(surface):
    """Convert a pygame surface into a cv image"""
    image_string = surface_to_string(surface)
    cv_image = cv.CreateImage(surface.get_size(), cv.IPL_DEPTH_8U, 3)
    cv.SetData(cv_image, image_string)
    return cv_image
 
def string_to_cvimage(string):
    """Convert a pygame surface into a cv image"""
    cv_image = cv.CreateImage(image_res2, cv.IPL_DEPTH_8U, 3)
    cv.SetData(cv_image, string)
    big_image = cv.CreateImage(SCREENSIZE, cv.IPL_DEPTH_8U, 3)
    cv.Resize(cv_image, big_image)
    return big_image

def cvimage_grayscale(cv_image):
    """Converts a cvimage into grayscale"""
    grayscale = cv.CreateImage(cv.GetSize(cv_image), 8, 1)
    cv.CvtColor(cv_image, grayscale, cv.CV_RGB2GRAY)
    return grayscale
 
def cvimage_to_pygame(image):
    """Convert cvimage into a pygame image"""
    image_rgb = cv.CreateMat(image.height, image.width, cv.CV_8UC3)
    cv.CvtColor(image, image_rgb, cv.CV_BGR2RGB)
    return pygame.image.frombuffer(image.tostring(), cv.GetSize(image_rgb),"RGB").convert()
 
def detect_faces(cv_image, storage):
    """Detects faces based on haar. Returns points"""
    small_image = cv.CreateImage(DETECTSIZE, cv.IPL_DEPTH_8U, 3)
    cv.Resize(cv_image, small_image)
    return cv.HaarDetectObjects(cvimage_grayscale(small_image), cascade,storage,1.1,3,cv.CV_HAAR_DO_CANNY_PRUNING,(40,40))

def draw_from_points(cv_image, points):
    """Takes the cv_image and points and draws a rectangle based on the points. Returns a cv_image."""
    for (x, y, w, h), n in points:
        new_x, new_y, new_w, new_h = scale_points(x,y,w,h)
        cv.Rectangle(cv_image, (new_x, new_y), (new_x + new_w, new_y + new_h), (0,255,0),2,4,0)
    return cv_image

def scale_points(x,y,w,h):
    new_x = int((float(x)/float(DETECTSIZE[0])) * SCREENSIZE[0])
    new_y = int((float(y)/float(DETECTSIZE[1])) * SCREENSIZE[1])
    new_w = int((float(w)/float(DETECTSIZE[0])) * SCREENSIZE[0])
    new_h = int((float(h)/float(DETECTSIZE[1])) * SCREENSIZE[1])

    return (new_x, new_y, new_w, new_h)

def faceRecogStuff(string):
    # Convert surface to cv image
    # cv_image = pygame_to_cvimage(string)
    cv_image = string_to_cvimage(string)    
    storage = cv.CreateMemStorage(0)  # Create storage
    points = detect_faces(cv_image, storage)  # Get points of faces.
    cv_image = draw_from_points(cv_image, points)  # Draw points
    return (cvimage_to_pygame(cv_image), points)
#============================================================================================================================

class Fish(pygame.sprite.Sprite):
    def __init__(self, num, word):    
        pygame.sprite.Sprite.__init__(self)
        self.num = num
        self.img = []
        self.angle = 0.0
        self.desired_angle = 0.0
        self.count = 0                  # Used to control duration of frames in sprite animation
        self.point = (0,0)              # Location of mouse click
        self.screensize = SCREENSIZE
        self.x_dir = 1              # X-Direction(+1:Left-to-Right, -1: Right-to-Left)
        self.y_dir = 1             # Y-Direction (+1: Down, -1: Up)
        self.z_dir = 1
        self.clock = pygame.time.Clock()
        self.r_click = False
        self.random_direction = False
        self.interact = False
        self.transparent = False
        self.word = WordleWord(word)

        for i in range(1, 9):           # Create each fish sprite ('filename of each frame',    duration_of_frame_in_seconds)
            self.img.append(('Images/Fish_GIF/Fish%s_%s.png'%(self.num, i), 0.2))
        self.fsh = pyganim.PygAnimation(self.img)
        
        self.width, self.height = self.fsh.getMaxSize()

        self.x_pos = random.uniform(self.width,self.screensize[0]-self.width)
        self.y_pos = random.uniform(self.height,self.screensize[1]-self.height)
        self.z_pos = random.randint(1,DEPTH)
                
        self.x_dir = random.choice([-1,1])
        #self.y_dir = random.choice([-1,1])
        #self.z_dir = random.choice([-1,1])
        
        self.impulse_vel = random.uniform(60, 100)       # Initial Velocity of fish caused by fin motion
        self.angle = random.uniform(-30,30) * math.pi / 180   # Angle fish swims (In Radians)
        
        self.x_speed = self.x_dir*(self.impulse_vel * math.cos(self.angle)) # Magnitude of Velocity in x-direction
        self.y_speed = (self.impulse_vel * math.sin(self.angle)) # Magnitude of Velocity in y-direction
        self.z_speed = random.uniform(-2,2)
        self.x_acc = -(WATER_RESIS * self.x_speed)
        #self.fsh.rotate(-self.angle) 

        ###NOTE: '-' implies fish moving up and '+' implies fish moving down
        if self.y_speed > 0:        #Fish moving Downwards  (y_speed is +ive)      
            self.y_acc = -(WATER_RESIS * self.y_speed) + (GRAVITY-BUYOANCY)
        else:                       #Fish moving Upwards  (y_speed is -ive)    
            self.y_acc = -(WATER_RESIS * self.y_speed) - (GRAVITY-BUYOANCY)  
                
        if self.x_dir < 0:
            self.fsh.flip(True, False)
        
        self.crit_vel = self.impulse_vel / 2.5           # Velocity at which fish flaps again        
        FISH_POSITIONS.append((self.x_pos, self.y_pos))    #Globally store each fish location
     
        self.fsh.play()                 # Begins playing the fish sprite
                 
    # Called in every iteration of the "game" loop, updates each fish.
    def update(self):
        if (self.x_pos + self.width >= self.screensize[0]+150) or (self.x_pos <= -150) or (random.randint(0,1000) == 30): #Fish go off edges before turning. Occasionally the fish turns randomly
            self.x_dir *= -1
            self.x_speed *= -1
            self.fsh.flip(True, False)   
        if self.y_pos + self.height > self.screensize[1] or self.y_pos < 0:
            #self.y_dir *= -1
            self.y_speed *= -1
            self.desired_angle = self.angle * -1
        if self.z_pos  >= DEPTH or self.z_pos <= 0:
            self.z_speed *= -1
            
        self.time_passed = self.clock.tick()    #unit is milliseconds
        self.time = self.time_passed / 1000.0   #unit is seconds    
        # print "Angle = ", -self.angle * 180/math.pi


        self.calculate_movement()               #Calculates the change in position of the fish over the recorded time interval
        #self.rotate()
        #self.scale()      

        
        #self.fsh.getRect().center = self.oldCenter
         
        
        self.x_pos += self.d_x
        self.y_pos += self.d_y
        self.z_pos += self.d_z
        FISH_POSITIONS[self.num-1] = (self.x_pos,self.y_pos)   
    
    def calculate_movement(self):
        
        if self.r_click:        #When a right click on screen
            if (math.fabs(self.x_pos +self.width/2 - self.point[0]) > 100 or (math.fabs(self.y_pos + self.height/2 - self.point[1]) > 100)):
                self.desired_angle = math.atan2((self.point[1] - self.y_pos),(self.point[0] - self.x_pos))    #Angle between two points
                self.x_speed = self.impulse_vel * math.cos(self.desired_angle) * 2    #Doubles motion towards mouse click
                self.y_speed = self.impulse_vel * math.sin(self.desired_angle) * 2    
                self.z_speed = 0
                if (self.x_dir > 0 and self.x_speed < 0) or (self.x_dir < 0 and self.x_speed > 0):  #If the click causes the fish to change direction
                    self.fsh.flip(True, False)
                    self.x_dir *= -1         
                #self.rotate()

            else:           # Now close to mouse click, fish wait until the click is released
                self.x_speed = 0
                self.y_speed = 0
                self.z_speed = 0
        
            self.d_x = (self.x_speed * self.time)   # Change in fish x_position
            self.d_y = (self.y_speed * self.time)   # Change in fish y_position    
            self.d_z = (self.z_speed * self.time)      
               
        elif self.random_direction:     # Called once right mouse button is released (fish to begin swimming again)
            self.new_x_dir = random.choice([-1,1])
            self.desired_angle = random.uniform(-30,30) * math.pi / 180   # Angle fish swims (In Radians)
            self.x_speed = self.new_x_dir*(self.impulse_vel * math.cos(self.desired_angle)) # Magnitude of Velocity in x-direction
            self.y_speed = self.impulse_vel * math.sin(self.desired_angle) # Magnitude of Velocity in y-direction
            self.z_speed = random.uniform(-2,2)
            #self.rotate() 
            if (self.new_x_dir != self.x_dir): # If fish is now swimming in the opposite direction
                self.fsh.flip(True, False)
                self.x_dir *= -1
            self.random_direction = False       # Only occurs once after right mouse button is released 

        elif self.interact:     # If a fish is clicked (Currently only flips fish, but could be developed)
            self.x_speed *= -1
            self.x_dir *= -1
            self.fsh.flip(True, False)
            self.interact = False
        
        else:       # Normal swimming, Without any interaction from user  
            self.d_x = (self.x_speed * self.time) + (0.5 * self.x_acc * math.pow(self.time,2))  #Current displacement is calculated using previously recorded values
            self.d_y = (self.y_speed * self.time) + (0.5 * self.y_acc * math.pow(self.time,2)) 
            self.d_z = (self.z_speed * self.time)
            if math.fabs(self.x_speed) < self.crit_vel: #Fish is now swimming too slow
                    self.desired_angle = random.uniform(-30,30) * math.pi / 180   # Angle fish swims (In Radians)
                    self.x_speed = self.x_dir*(self.impulse_vel * math.cos(self.desired_angle)) # Magnitude of Velocity in x-direction
                    self.y_speed = self.impulse_vel * math.sin(self.desired_angle) # Magnitude of Velocity in y-direction
                #    print "Desired Angle", self.desired_angle * 180/math.pi
                    self.count = 0      # Reset the counter
                    self.fsh.rate = 1   # Speed up animation frames to coincide with increased speed                         

            else:
                if self.count > 10:     # Once count has exceeds 10, animation returns to normal speed 
                    self.fsh.rate = 0.2      
                self.x_speed += self.time*self.x_acc    # v=u+at
                self.y_speed += self.time*self.y_acc    # Since up is negative and down is positive 
                #self.angle = math.atan2(math.fabs(self.y_speed), math.fabs(self.x_speed))
                #self.fsh.rotate(self.angle * -self.y_dir)
                self.count += 1
            
            #self.rotate()

        #    if self.x_dir < 0:
        #        self.fsh.flip(True, False)              
            self.x_acc = -(WATER_RESIS * self.x_speed)
            if self.y_speed > 0:        #Fish moving Downwards  (y_speed is +ive)      
                self.y_acc = -(WATER_RESIS * self.y_speed) - (GRAVITY-BUYOANCY)
            else:                       #Fish moving Upwards  (y_speed is -ive)    
                self.y_acc = -(WATER_RESIS * self.y_speed) + (GRAVITY-BUYOANCY)  

    def scale(self):
        #self.multiplier = self.z_pos/20
        self.width, self.height = self.fsh.getMaxSize()
        self.fsh.scale((self.width - int(self.z_pos), self.height - int(self.z_pos)))
        # if self.transparent:
        #     self.fsh.make_transparent(0)
        # if self.x_dir < 0:
        #     self.fsh.flip(True, False)
    
    def rotate(self):
        #print math.fabs(math.fabs(self.angle) - math.fabs(self.desired_angle))
        if math.fabs(self.angle - self.desired_angle) > 0.1:
            if self.desired_angle > self.angle:
                self.fsh.rotate(-(self.angle + 0.05))
                self.angle += 0.05
            else:
                self.fsh.rotate(-(self.angle - 0.05))
                self.angle -= 0.05
            if self.transparent:
                self.fsh.make_transparent(0)
            if self.x_dir < 0:
                self.fsh.flip(True, False)
                
    def swim_to_point(self, points):
        p, _ = points[0]
        x,y,w,h = p
        x,y,w,h = scale_points(x,y,w,h)
        # print x,y,w,h
        x_diff = x - w/2
        y_diff = y - h
        mouse_point = (x+x_diff,y-y_diff)
        #mouse_point = (x,y)
        self.point = mouse_point
        self.r_click = True 

    def check_for_interaction(self, point):
        if (math.fabs(self.x_pos + self.width/2 - point[0]) < 50) and (math.fabs(self.y_pos + self.height/2 - point[1]) < 50):
            self.interact = True
            return True
        else:
            return False
        
    def left_release(self): 
        self.interact = False
        
    def right_release(self):
        self.r_click = False    
        # self.random_direction = True

            
    def blit(self, screen):             # Pastes fish onto screen
        #print self.z_pos
        self.fsh.blit(screen, self.get_pos())
    
    def get_pos(self):
        return (self.x_pos, self.y_pos)

    def make_transparent(self):
        self.fsh.make_transparent(0) # Calls the pyganim.py method
        self.transparent = True

    def reset_colour(self):
        self.fsh.clearTransforms()  # Returns original images (which may need to be flipped)
        self.transparent = False
        if self.x_speed < 0:
            self.fsh.flip(True, False)

class Bubble(pygame.sprite.Sprite):
    def __init__(self, word):    
        pygame.sprite.Sprite.__init__(self)
        self.clock = pygame.time.Clock()
        self.screensize = SCREENSIZE
        self.img = []
        
        for i in range(1, 26):
            self.img.append(('Images/Bubble_GIF/Bubble2_%s.png'%(i), 0.2))   # Load Each Frame
        self.bub = pyganim.PygAnimation(self.img)

        self.width, self.height = self.bub.getMaxSize()

        self.bub.play()     # Play the Bubble Animation
        self.multiplier = SCREENSIZE[1]/self.height
        self.bub.scale([self.width*self.multiplier,self.height*self.multiplier])  # Make Bubbles go to top of screen
        
    def blit(self, screen, pos):     # Paste Bubble animation onto screen
        self.bub.blit(screen, pos)
    
    def make_transparent(self):
        self.bub.make_transparent(0) 
        
    def reset_bubble(self):
        self.bub.clearTransforms()
        self.bub.scale([self.width*self.multiplier,self.height*self.multiplier])  # Make Bubbles go to top of screen


class VideoFishTank(object):
    def __init__(self, **argd):
        self.__dict__.update(**argd)
        super(VideoFishTank, self).__init__(**argd)
        self.screen = pygame.display.set_mode(SCREENSIZE)
        pygame.display.set_caption('The SAP Fish Tank') 
        self.orig_air_bubble = pygame.image.load('Images/Bubble.png').convert_alpha()
        self.emit_word = []
        self.transparency = []
        self.air_bubble = []
        self.bubble_location = []
        self.bubble_size = []
        self.word = []
        for i in range(NUM_FISH):
            self.emit_word.append(False)
            self.transparency.append(255)
            self.air_bubble.append(self.orig_air_bubble)
            self.bubble_size.append(5)
            self.bubble_location.append([0,0])
            self.word.append(pygame.image.load(WORDS[i]).convert_alpha())

        self.clock = pygame.time.Clock()
        self.count = COUNT

        #self.init_camera()        
              
    def init_camera(self):
        pygame.camera.init()
        self.cam_list = pygame.camera.list_cameras()         # Gets a list of available cameras       
        if not self.cam_list:
            raise ValueError("Sorry, no cameras detected.") 
        self.cam_id = self.cam_list[0]
        self.cam = pygame.camera.Camera(self.cam_id, SCREENSIZE)
        self.cam.start()
    
    def setup_fishtank(self):   # These remain stationary, therefore can be recalled when resetting fish tank transparency
        ###CODE FOR ANIMATED OCEAN IF USED
        self.img = []
        for i in range(1, 10):
            self.img.append(('Images/Ocean_GIF/ocean%s.png'%(i), 0.2))
        self.ocean = pyganim.PygAnimation(self.img)
        self.ocean.scale(SCREENSIZE)
        self.ocean.make_transparent(100)
        self.ocean.play()
        #self.ocean = pygame.image.load('Images/Ocean_1.png').convert_alpha()    # Load image
        #self.ocean = pygame.transform.scale(self.ocean,SCREENSIZE)      # Ensure image is same size as screen
        #self.ocean.fill((255, 255, 255, 170), None, pygame.BLEND_RGBA_MULT)  # Make slightly transparent (170) to allow for the live video stream to be seen 
        
        #self.depth = []                        
        #for i in range(50):
        #    self.depth.append(pygame.Surface(SCREENSIZE,pygame.SRCALPHA, 32).convert_alpha())
        
        self.foreground = pygame.image.load('Images/Fish_Tank_Bed.png').convert_alpha() 
        self.foreground = pygame.transform.scale(self.foreground,(SCREENSIZE[0],int(SCREENSIZE[1]/1.5)))
        self.foreground.fill((255, 255, 255, 255), None, pygame.BLEND_RGBA_MULT)
        
    def setup_fish(self):   #Can only be used for initial setup, as fish are moving 
        self.fish = [Fish(n, 'word%d' % n) for n in xrange(1,1+NUM_FISH)]    #Load the chosen number of fish

    def setup_bubbles(self):
        self.bubble = Bubble(None)  

    def make_transparent(self): #Makes full fish tank overlay transparent
        self.foreground.fill((255, 255, 255, 0), None, pygame.BLEND_RGBA_MULT)
        #self.ocean.fill((255, 255, 255, 150), None, pygame.BLEND_RGBA_MULT) 
        self.ocean.make_transparent(0)
        self.bubble.make_transparent()
        for fsh in self.fish:
            fsh.make_transparent()
            
    def reset_tank(self):   #Remove transparency and return fish tank overlay
        self.setup_fishtank()
        self.bubble.reset_bubble()
        for fsh in self.fish:
            fsh.reset_colour()  
    
    def update(self, chk, state, av, queue):   #Iterative Loop
        previouscreen = None
        smallscreen = None
        #for i in range(50):
        #    self.depth[i].fill(255)
        #    self.depth[i].set_alpha(255)
            
        # self.background = self.cam.get_image()  #Captures current video frame
        # self.background = pygame.transform.scale(self.background,SCREENSIZE)    

        data = get_frame(self.address)

        # if self.count > 0:
        #     background = string2Surface(data)
        #     self.count -= 1
        # else:
        #     background = faceRecogStuff(data)
        #     self.count = COUNT
        background, points = faceRecogStuff(data)

        # Pull local frame off queue
        if queue.full():
            smallscreen = queue.get()
            smallscreen = string2Surface(smallscreen)
            # Make it the smaller size
            smallscreen = pygame.transform.scale(smallscreen, smallres)
        else:
            smallscreen = previouscreen

        #Paste all layers on screen
        self.screen.blit(background,(0,0))
        #self.screen.blit(self.ocean,(0,0))
        self.ocean.blit(self.screen,(0,0))    # Used if Ocean is animated           
        #for i in range(50):
        #    self.screen.blit(self.depth[i], (0,0))
        self.screen.blit(self.foreground,(0,int(SCREENSIZE[1] - SCREENSIZE[1]/1.5)))
        self.bubble.blit(self.screen, (100,50))
        
        if random.randint(0,10) == 5:
            self.choice = random.randint(0, NUM_FISH-1)
            self.chosen_fish = self.fish[self.choice]
            if self.chosen_fish.y_pos < SCREENSIZE[1]/3 or self.chosen_fish.x_pos > SCREENSIZE[0]-150 or self.chosen_fish.x_pos < 150:
                pass
            elif self.emit_word[self.choice] == True:
                pass
            else:
                self.transparency[self.choice] = 255
                self.emit_word[self.choice] = True
                self.bubble_size[self.choice] = 5
                if (self.chosen_fish.x_speed < 0):
                    self.bubble_location[self.choice] = [self.chosen_fish.x_pos, self.chosen_fish.y_pos + self.chosen_fish.height/2]
                else:
                    self.bubble_location[self.choice] = [self.chosen_fish.x_pos + self.chosen_fish.width, self.chosen_fish.y_pos + self.chosen_fish.height/2]

        for i in range(len(self.emit_word)):
            if self.emit_wor
            d[i]:
                self.emit(i)
              
        for fish in self.fish:
            fish.blit(self.screen)
            if points:
                fish.swim_to_point(points)
            else:
                fish.right_release()
            fish.update()

        if smallscreen:
            previouscreen = smallscreen
            self.screen.blit(smallscreen,(SCREENSIZE[0]-smallres[0]-10,SCREENSIZE[1]-smallres[1]-10))
        elif previouscreen:
            self.screen.blit(previouscreen,(SCREENSIZE[0]-smallres[0]-10,SCREENSIZE[1]-smallres[1]-10))

        if chk >= 0 and state == 'word':
            self.fish[chk].word.display(self.screen)
        elif chk >= 0 and state == 'user':
            self.fish[chk].word.associated[av].display(self.screen)

        self.clock.tick()
        print self.clock.get_fps()

        pygame.display.update()   

        
    def emit(self, choice):
        
        self.air_bubble[choice] = self.orig_air_bubble
        self.air_bubble[choice] = pygame.transform.scale(self.air_bubble[choice], (self.bubble_size[choice],self.bubble_size[choice]))
        self.air_bubble[choice].fill((255, 255, 255, self.transparency[choice]), None, pygame.BLEND_RGBA_MULT)
        self.bubble_location[choice][1] -= 8 
        self.screen.blit(self.air_bubble[choice],self.bubble_location[choice])

        self.bubble_size[choice] += 2
        if self.bubble_size[choice] <= 10:
            self.bubble_location[choice][0] += self.fish[choice].d_x

        else:
            self.word[choice] = pygame.image.load(WORDS[choice-1]).convert_alpha()

            self.word[choice].fill((255, 255, 255, self.transparency[choice]), None, pygame.BLEND_RGBA_MULT)

            self.word_width, self.word_height = self.word[choice].get_size()
            self.bubble_width, self.bubble_height = self.air_bubble[choice].get_size()
            self.scaler = float(self.word_width) / float(self.bubble_size[choice])
            self.word[choice] = pygame.transform.scale(self.word[choice], (int(self.word_width / self.scaler), int(self.word_height / self.scaler)) )
            self.screen.blit(self.word[choice],(self.bubble_location[choice][0], self.bubble_location[choice][1] + (self.bubble_height/2 - int(self.word_height / self.scaler)/2))) #[0]- self.width/2, self.bubble_location[1] - self.height/2))
            if self.bubble_size[choice] >= 60:
                self.bubble_size[choice] -= 2
                self.transparency[choice] -= 10
            if self.transparency[choice] < 0:
                self.emit_word[choice] = False
                    
    def main(self, addr, que):
        self.setup_fishtank()
        self.setup_fish()
        self.setup_bubbles()

        self.address = addr
        
        av = -1
        choice = -1
        state = 'tank'

        while True: #Game Loop - Detects Key Presses and Mouse Clicks 
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.display.quit()
                    exit()
                elif pygame.key.get_pressed()[K_UP]:
                    self.make_transparent()
                elif pygame.key.get_pressed()[K_DOWN]:
                    self.reset_tank()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:   #Left Clicks
                        if state == "tank":
                            for i in  xrange(len(self.fish)):
                                chk = self.fish[i].check_for_interaction(event.pos)   #Check if click is over a fish
                                print "Chk, i, state:",chk,i, state
                                if chk:
                                    state, av = self.fish[i].word.change_state(state, event.pos)
                                    choice = i
                        else:
                            state, av = self.fish[i].word.change_state(state, event.pos)
                    elif event.button == 3: #Right Click
                        for fish in self.fish:
                            fish.swim_to_point(event.pos)   #Get all fish to swim towards point
                elif event.type == pygame.MOUSEBUTTONUP:    #After mouse button has been released
                    if event.button == 1:
                        for fish in self.fish:
                            fish.left_release()                    
                    if event.button == 3:
                        for fish in self.fish:
                            fish.right_release()

            self.update(choice, state, av, que)
            
def main():  
    pygame.init()
    VideoFishTank().main()
    pygame.quit()

if __name__ == "__main__":
    main()